<template>
  <div v-if="editOpen" style="width: 100%;">
    <t-dialog
      :header="header"
      :visible.sync="visible"
      :onClose="onClose"
      width="80%"
      top="5%"
    >
      <div v-if="rowIndex==null">
        <t-alert style="margin-bottom: 20px" theme="info"
                 :message="`当前页面可重复添加。目前已添加数量: ${data.length} `"/>
      </div>
      <t-form ref="form" resetType="initial" :data="formData" labelWidth="160px" :rules="rules">
        <t-row style="row-gap:24px">
          <t-col :span="6">
            <t-form-item label="姓名" name="name">
              <t-select
                v-model="formData.name"
                creatable
                filterable
                @change="onLeaderNameChange"
                placeholder="请输入姓名"
                :loading="nameLoading"
                @search="remoteNameMethod"
                :options="nameOptions"
                @create="createNameOptions"
                style="width: 390px"
              />
            </t-form-item>
          </t-col>
          <t-col :span="6">
            <t-form-item label="身份证号" name="idCard">
              <t-input style="width: 390px"  @change="onIdCardChange"  placeholder="请输入身份证号" clearable v-model="formData.idCard"></t-input>
            </t-form-item>
          </t-col>
          <t-col :span="6">
            <t-form-item label="出生年月" name="birthDate">
              <t-date-picker
                disabled
                :disable-date="{
        after: dayjs().endOf('month').add(-18, 'year').format()}"
                clearable allow-input
                style="width: 390px"
                mode="month"
                v-model="formData.birthDate"></t-date-picker>
            </t-form-item>
          </t-col>
          <t-col :span="6">
            <t-form-item label="性别" name="sex">
              <t-select clearable style="width:390px" :options="dictTypes.sys_user_sex"
                        v-model="formData.sex"></t-select>
            </t-form-item>
          </t-col>
          <t-col :span="6">
            <t-form-item label="职务" name="duty">
              <t-input clearable style="width:390px" v-model="formData.duty"
              ></t-input>
            </t-form-item>
          </t-col>
          <t-col :span="6">
            <t-form-item label="学历" name="education">
              <t-select style="width: 390px" v-model="formData.education" clearable
                        placeholder="请选择学历"
                        :options="dictTypes.education">
              </t-select>
            </t-form-item>
          </t-col>
          <t-col :span="6">
            <t-form-item label="学位" name="degree">
              <t-select style="width: 390px" v-model="formData.degree" clearable
                        placeholder="请选择学历"
                        :options="dictTypes.degree">
              </t-select>
            </t-form-item>
          </t-col>
          <t-col :span="6">
            <t-form-item label="技术职称" name="profTitId">
              <t-tree-select style="width:390px" @change="onProfTitIdChange" clearable filterable
                             :treeProps="{keys: {value: 'id',label:'name'}, valueMode: 'onlyLeaf'}"
                             v-model="formData.profTitId" :data="profTitOptions" placeholder="技术职称"></t-tree-select>
            </t-form-item>
          </t-col>
          <t-col :span="6">
            <t-form-item label="职称" name="profTit">
              <t-select disabled style="width:390px" v-model="formData.profTit" clearable placeholder="请选择职称"
                        :options="dictTypes.prof_tit"></t-select>
            </t-form-item>
          </t-col>
          <t-col :span="6">
            <t-form-item label="所学专业" name="majorName">
              <t-input
                v-model="formData.majorName"
                clearable
                placeholder="请输入专业"
                style="width: 390px"
              />
            </t-form-item>
          </t-col>
          <t-col :span="6">
            <t-form-item label="现从事专业" name="majorNowName">
              <t-input
                v-model="formData.majorNowName"
                clearable
                placeholder="请输入专业"
                style="width: 390px"
              />
            </t-form-item>
          </t-col>
          <t-col :span="6">
            <t-form-item label="所在单位" help="搜索不到请切换外部单位后手输" name="company">
              <t-tree-select @change="(val,content)=>{formData.companyId=content.node.data.id}" v-if="formData.isInnerCompany==='1'" style="width:390px" clearable filterable
                             :treeProps="{keys: {value: 'label'}}" v-model="formData.company" :data="deptMenuOptions"
                             placeholder="选择单位">
                <template #label>
                  <t-switch
                    size="medium"
                    v-model="formData.isInnerCompany"
                    :label="['内部', '外部']"
                    :customValue="['1', '0']"
                    @change="()=>{formData.company='';formData.companyId=null}"
                  ></t-switch>
                </template>
              </t-tree-select>
              <t-select
                v-else
                v-model="formData.company"
                creatable
                filterable
                placeholder="请输入"
                @change="(val,content)=>{formData.companyId = content.option?.id}"
                :loading="companyLoading"
                @search="remoteCompanyMethod"
                :options="companyOptions"
                @create="createCompanyOptions"
                style="width: 390px"
              >
                <template #label>
                  <t-switch
                    size="medium"
                    v-model="formData.isInnerCompany"
                    :label="['内部', '外部']"
                    :customValue="['1', '0']"
                    @change="()=>{formData.company='';formData.companyId=null}"
                  ></t-switch>
                </template>
              </t-select>
            </t-form-item>
          </t-col>
          <t-col :span="6">
            <t-form-item label="在本奖励中承担的任务" name="task">
              <t-input style="width:390px" clearable v-model="formData.task" placeholder="请输入"></t-input>
            </t-form-item>
          </t-col>
        </t-row>
      </t-form>
      <template #footer>
        <t-button theme="default" @click="onClose">取消</t-button>
        <t-button theme="primary" @click="onSubmit(1)">保存</t-button>
        <t-button theme="primary" @click="onSubmit(2)">保存并继续添加</t-button>
      </template>
    </t-dialog>
    <t-row style="align-items: stretch" :gutter="14">
      <t-col :span="12">
        <t-table size="small"  :loading="dataLoading" :selected-row-keys="selectedRowKeys"
                 @select-change="(val)=>{selectedRowKeys=val}" rowKey="id" :data="data"
                 :columns="columns">
          <template #index="{ rowIndex }">
            {{ rowIndex + 1 }}
          </template>
          <template #name="{ row }">
            <t-link @click="dialog.objId=row.idCard;dialog.header=row.name;dialog.open_detail=true" hover="color" theme="primary">{{ row.name }}</t-link>
          </template>
          <template #sex="{ row }">
            {{ row.sex | filterByDict(dictTypes.sys_user_sex) }}
          </template>
          <!--          <template #profTit="{ row }">-->
          <!--            {{ row.profTit | filterByDict(dictTypes.prof_tit) }}-->
          <!--          </template>-->
          <template #profTitId="{ row }">
            {{ row.profTitId | filterByTree(profTitOptions, children = "children", id = "id", label = "name") }}({{ row.profTit | filterByDict(dictTypes.prof_tit) }})
          </template>
          <template #education="{ row }">
            {{ row.education | filterByDict(dictTypes.education) }}
          </template>
          <template #degree="{ row }">
            {{ row.degree | filterByDict(dictTypes.degree) }}
          </template>
        </t-table>
        <div style="margin-top: 10px" class="btn-group-inline">
          <t-button @click="header='新增获奖人员';rowIndex=null;visible=true;visible=true">新增
          </t-button>
          <t-button @click="upMember">上移</t-button>
          <t-button @click="downMember">下移</t-button>
          <t-button @click="updateMember">修改</t-button>
          <t-button @click="delMember">删除</t-button>
        </div>
      </t-col>
    </t-row>
  </div>
  <div v-else style="width: 100%;">
    <t-row style="align-items: stretch" :gutter="14">
      <t-col :span="12">
        <t-table size="small" :loading="dataLoading" :selected-row-keys="selectedRowKeys"
                 @select-change="(val)=>{selectedRowKeys=val}" rowKey="id" :data="data"
                 :columns="columns9">
          <template #index="{ rowIndex }">
            {{ rowIndex + 1 }}
          </template>
          <template #name="{ row }">
            <t-link @click="dialog.objId=row.idCard;dialog.header=row.name;dialog.open_detail=true" hover="color" theme="primary">{{ row.name }}</t-link>
          </template>
          <template #sex="{ row }">
            {{ row.sex | filterByDict(dictTypes.sys_user_sex) }}
          </template>
          <template #profTitId="{ row }">
            {{ row.profTitId | filterByTree(profTitOptions, children = "children", id = "id", label = "name") }}({{ row.profTit | filterByDict(dictTypes.prof_tit) }})
          </template>
          <!--          <template #profTit="{ row }">-->
          <!--            {{ row.profTit | filterByDict(dictTypes.prof_tit) }}-->
          <!--          </template>-->
          <template #education="{ row }">
            {{ row.education | filterByDict(dictTypes.education) }}
          </template>
          <template #degree="{ row }">
            {{ row.degree | filterByDict(dictTypes.degree) }}
          </template>
        </t-table>
      </t-col>
    </t-row>
    <member-all-detail :header="dialog.header" :objId="dialog.objId" :visible.sync="dialog.open_detail" v-if="dialog.open_detail"></member-all-detail>
  </div>
</template>

<script>
import {getDictList} from "@/api/system/dict/data";
import dayjs from "dayjs"
import {getIdCardBirthday, getIdCardAge} from '@/utils/common';
import memberAllDetail from "@/pages/common/system/components/member-all-detail.vue";


export default {
  name: "awards-member",
  components: {
    memberAllDetail
  },
  props: {
    value: Array,
    objId: [String, Number],
    editOpen: {
      type: Boolean,
      default: false
    },
    phaseType: {
      type: String,
      default: '1'
    }
  },
  data() {
    return {
      dataLoading: false,
      companyLoading: false,
      companyOptions: [],
      nameLoading: false,
      nameOptions: [],
      dialog: {
        objId: null,
        header: '',
        open_detail: false,
        name: '',
        openSearchMember: false,
        type: ''
      },
      rowIndex: null,
      dayjs,
      visible: false,
      header: "添加",
      profTitOptions: [],
      deptMenuOptions: [],
      dictTypes: {},
      formData: {
        companyId: null,
        name: '',
        sex: '1',
        birthDate: '',
        degree: '',
        duty: '',
        profTit: '',
        profTitId: null,
        majorName: '',
        majorNowName: '',
        company: '',
        task: '',
        education: '',
        idCard: '',
        isAssist: '0',
        isInnerCompany: '1'
      },
      rules: {
        name: [
          {
            required: true,
            message: "姓名不能为空",
          }
        ],
        sex: [
          {
            required: true,
            message: "性别不能为空",
          }
        ],
        birthDate: [
          {
            required: true,
            message: "出生年月不能为空",
          }
        ],
        duty: [
          {
            required: true,
            message: "职务不能为空",
          }
        ],
        profTit: [
          {
            required: true,
            message: "职称不能为空",
          }
        ],
        profTitId: [
          {
            required: true,
            message: "技术职称不能为空",
          }
        ],
        degree: [{
          required: true,
          message: "学位不能为空",
        }],
        education: [{
          required: true,
          message: "学历不能为空",
        }],
        majorName: [
          {
            required: true,
            message: "所学专业不能为空",
          }
        ],
        majorNowName: [
          {
            required: true,
            message: "现从事专业不能为空",
          }
        ],
        company: [
          {
            required: true,
            message: "所在单位不能为空",
          }
        ],
        task: [
          {
            required: true,
            message: "在本奖励中承担的任务不能为空",
          }
        ],
        isInnerCompany: [
          {
            required: true,
            message: "不能为空",
          }
        ],
        idCard: [
          {
            required: true,
            message: "身份证号不能为空",
          },
          {
            message: "身份证号不正确",
            pattern: /^\d{6}((((((19|20)\d{2})(0[13-9]|1[012])(0[1-9]|[12]\d|30))|(((19|20)\d{2})(0[13578]|1[02])31)|((19|20)\d{2})02(0[1-9]|1\d|2[0-8])|((((19|20)([13579][26]|[2468][048]|0[48]))|(2000))0229))\d{3})|((((\d{2})(0[13-9]|1[012])(0[1-9]|[12]\d|30))|((\d{2})(0[13578]|1[02])31)|((\d{2})02(0[1-9]|1\d|2[0-8]))|(([13579][26]|[2468][048]|0[048])0229))\d{2}))(\d|X|x)$/,
          },
        ],
      },
      data: [],
      columns: [
        {
          colKey: 'row-select',
          type: 'single',
          title: "选择",
          width: 64
        },
        {
          colKey: 'index',
          title: "序号",
          align: "center",
          width: 64
        },
        {
          colKey: "name",
          title: "姓名",
          align: "center",
          width: 100
        },
        {
          colKey: "sex",
          title: "性别",
          align: "center",
          width: 60
        },
        {
          colKey: "idCard",
          title: "身份证号",
          align: "center",
          width: 180
        },
        {
          colKey: "birthDate",
          title: "出生年月",
          align: "center",
          width: 100
        },

        {
          colKey: "duty",
          title: "职务",
          align: "center",
          width: 100
        },
        {
          colKey: "profTitId",
          title: "技术职称",
          align: "center",
          width: 130
        },
        // {
        //   colKey: "profTit",
        //   title: "职称",
        //   align: "center",
        //   width: 100
        // },
        {
          colKey: "education",
          title: "学历",
          align: "center",
          width: 100
        },
        {
          colKey: "degree",
          title: "学位",
          align: "center",
          width: 100
        },
        {
          colKey: "majorName",
          title: "所学专业",
          align: "center",
        },
        {
          colKey: "majorNowName",
          title: "现从事专业",
          align: "center",
        },
        {
          colKey: "company",
          title: "所在单位",
          align: "center",
        },
        {
          colKey: "task",
          title: "在本奖励中承担的任务",
          align: "center",
          width: 200
        },
      ],
      columns9: [
        {
          colKey: 'index',
          title: "序号",
          align: "center",
          width: 64
        },
        {
          colKey: "name",
          title: "姓名",
          align: "center",
          width: 100
        },
        {
          colKey: "sex",
          title: "性别",
          align: "center",
        },
        {
          colKey: "idCard",
          title: "身份证号",
          align: "center",
          width: 180
        },
        {
          colKey: "birthDate",
          title: "出生年月",
          align: "center",
        },

        {
          colKey: "duty",
          title: "职务",
          align: "center",
        },
        {
          colKey: "profTitId",
          title: "技术职称",
          align: "center",
          width: 130
        },
        // {
        //   colKey: "profTit",
        //   title: "职称",
        //   align: "center",
        // },
        {
          colKey: "education",
          title: "学历",
          align: "center",
          width: 100
        },
        {
          colKey: "degree",
          title: "学位",
          align: "center",
          width: 100
        },
        {
          colKey: "majorName",
          title: "所学专业",
          align: "center",
        },
        {
          colKey: "majorNowName",
          title: "现从事专业",
          align: "center",
        },
        {
          colKey: "company",
          title: "所在单位",
          align: "center",
        },
        {
          colKey: "task",
          title: "在本奖励中承担的任务",
          align: "center",
          width: 200
        },
      ],
      selectedRowKeys: [],
      selectedMember1RowKeys: [],
    }
  },
  watch: {
    objId: {
      immediate: true,
      handler(val) {
        if (val) {
          this.getMemberList(val);
        }
      }
    },
    data: {
      deep: true,
      immediate: true,
      handler(val) {
        const newData = this.data.map((val, index) => ({...val, sort: index + 1}))
        this.$emit("input", newData);
      }
    },
  },
  methods: {
    onIdCardChange(val) {
      const birthday = getIdCardBirthday(val);
      if (birthday !== "") {
        this.formData.birthDate = birthday.slice(0, 7);
      }
    },
    createCompanyOptions(value) {
      this.companyOptions.push({
        label: `${value}`,
        value,
      });
    },
    remoteCompanyMethod(search) {
      this.companyLoading = true;
      this.$api.system.dept.selectAllOutDeptList({deptName: search}).then(response => {
        this.companyOptions = response.data.map(val => ({
          ...val,
          label: `${val.deptName}`,
          value: val.deptName,
        }));
        this.companyLoading = false;
      }).catch((e) => {
        this.companyLoading = false;
        this.$message.error(e.toString());
      });
    },
    onLeaderNameChange(val, content) {
      const index = this.nameOptions.findIndex(val => content.option?.id === val.id)
      this.nameOptions[index].label = this.nameOptions[index].name;
      this.$set(this.nameOptions, index, this.nameOptions[index])
      Object.assign(this.formData, content.option || this.nameOptions[index])
    },
    createNameOptions(value) {
      this.nameOptions.push({
        label: `${value}`,
        value,
        name: value
      });
    },
    remoteNameMethod(search) {
      this.nameLoading = true;
      this.$api.system.member.searchList({name: search}).then(response => {
        this.nameOptions = response.data.map(val => ({
          ...val,
          label: `${val.name}-${val.idCard}`,
          value: `${val.name}-${val.idCard}`,
        }));
        this.nameLoading = false;
      }).catch((e) => {
        this.nameLoading = false;
        this.$message.error(e.toString());
      });
    },
    onProfTitIdChange(val, content) {
      this.formData.profTit = content.node.data.level;
    },
    getDeptTreeSelect() {
      return this.$api.system.dept.treeSelectAllIn().then(response => {
        this.deptMenuOptions = response.data;
        // this.menuOptions = this.handleTree(response.data, "id");
      }).catch((e) => {
        this.$message.error(e.toString());
      });
    },
    getDataTypes() {
      return getDictList(["sys_user_sex", "prof_tit", "degree", "duty", "education"]).then(response => {
        this.dictTypes = response.data;
      }).catch((e) => {
        this.$message.error(e.toString());
      });
    },
    getProfTitTreeSelect() {
      return this.$api.system.profTit.list().then(response => {
        this.profTitOptions = this.handleTree(response.data, "id");
      }).catch((e) => {
        this.$message.error(e.toString());
      });
    },
    async getMemberList() {
      if (this.objId) {
        this.dataLoading = true;
        Promise.all([this.getDataTypes(), this.getDeptTreeSelect(), this.getProfTitTreeSelect()]);
        this.$api.cgzh.awards.memberListGet(this.objId).then(response => {
          this.data = response.data;
          this.dataLoading = false;
        }).catch((e) => {
          this.dataLoading = false;
          this.$message.error(e.toString());
        });
      }
    },
    upMember() {
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning("请选择一行");
        return;
      }
      const data = this.data.filter((val) => ['1'].includes(val.type));
      if (data.length > 0) {
        if (this.data[1].id === this.selectedRowKeys[0]) {
          this.$message.warning("已是第一行");
        } else {
          const index = this.data.findIndex((val) => val.id === this.selectedRowKeys[0])
          this.moveInArray(this.data, index, index - 1)
        }
      } else {
        if (this.data[0].id === this.selectedRowKeys[0]) { // eslint-disable-line
          this.$message.warning("已是第一行");
        } else {
          const index = this.data.findIndex((val) => val.id === this.selectedRowKeys[0])
          this.moveInArray(this.data, index, index - 1)
        }
      }

    },
    downMember() {
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning("请选择一行");
        return;
      }
      if (this.data[this.data.length - 1].id === this.selectedRowKeys[0]) {
        this.$message.warning("已是最后一行");
      } else {
        const index = this.data.findIndex((val) => val.id === this.selectedRowKeys[0])
        this.moveInArray(this.data, index, index + 1)
      }
    },
    updateMember() {
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning("请选择一行");
        return false;
      }
      const index = this.data.findIndex((val) => val.id === this.selectedRowKeys[0])
      Object.assign(this.formData, this.data[index])
      this.rowIndex = index;
      this.header = "修改获奖人员"
      this.visible = true;
      this.visible = true;

    },
    delMember() {
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning("请选择一行");
        return;
      }
      const index = this.data.findIndex((val) => val.id === this.selectedRowKeys[0])
      this.data.splice(index, 1)
      this.selectedRowKeys = [];
    },
    moveInArray(arr, ffrom, to) {
      // 删除当前的位置
      const item = arr.splice(ffrom, 1);
      // 确保还剩有元素移动
      if (!item.length) {
        this.$message.warning(`There is no item in the array at index ${ffrom}`);
      }
      // 移动元素到指定位置
      arr.splice(to, 0, item[0]);
    },
    onSubmit(type) {
      this.$refs.form.validate().then((validateResult) => {
        if (validateResult === true) {
          if (this.rowIndex !== null) {
            this.$set(this.data, this.rowIndex, {
              awardsId: this.objId,
              ...this.formData,
            })
            this.$message.success("修改成功");
            this.rowIndex = null;
            if(type === 1){
              this.onClose();
            }
          } else {
            const newId = Number(new Date().getTime()) + Number(Math.random() * 10)
            this.data.push({
              ...this.formData,
              id: newId,
              awardsId: this.objId,
            })
          }
          this.$refs.form.reset();
          if (type === 1) {
            this.onClose()
          }
        } else {
          const firstError = Object.values(validateResult)[0]?.[0]?.message;
          this.$message.error(firstError);
        }
      })
    },
    onClose() {
      this.$refs.form.reset();
      this.visible = false;
    }
  }
}
</script>

<style lang="less" scoped>
.step-form {
  padding: 0 24px;
}

.t-row {
  margin-bottom: 14px;
}

.step-card {
  height: 100%;
  margin-bottom: 14px;
}
</style>
